<?php
namespace app\api\controller;

use think\Request;

class Settlement extends BaseController
{
    private $_data = array (
        'data' => null,
        'error' => null
    );

    public function getCheckInDate()
    {
        $data = [];

        if (Request::instance()->isPost()) {
            $room_id = input('post.room_id');
            $check_in_id = input('post.check_in_id');

            $check_in_model = model('CheckIn');

            $check_in_data = $check_in_model->get(['check_in_id' => $check_in_id, 'room_id' => $room_id, 'is_deleted' => '0']);
            $data['check_in_date'] = date('Y-m-d', $check_in_data['check_in_date']);
            $data['check_out_date'] = !$check_in_data['check_out_date'] ? date('Y-m') : date('Y-m', $check_in_data['check_out_date']);
            $data['status'] = 200;
        }

        return json($this->dataReturn($data));
    }

    public function create()
    {
        $result = false;

        if (Request::instance()->isPost()) {
            $data = [];
            $data['error'] = [];

            $user_id = input('post.user_id');
            $room_id = input('post.room_id');
            $check_in_id = input('post.check_in_id');
            $settlement_month = input('post.settlement_month');
            $settlement_electricity = input('post.settlement_electricity');
            $settlement_water = input('post.settlement_water');
            $settlement_additional_amount = input('post.settlement_additional_amount');
            $settlement_remark = input('post.settlement_remark');

            $settlement_month = strtotime($settlement_month);

            //该月份是否已结算
            $settlement_model = model('Settlement');
            $settlement_data = $settlement_model->get([
                'user_id' => $user_id,
                'room_id' => $room_id,
                'check_in_id' => $check_in_id,
                'settlement_month' => $settlement_month
            ]);
            if ($settlement_data) $this->_data['error']['message'] = '该月份已结算';

            if (!$data['error']) {
                //房间信息
                $room_model = model('Room');
                $room_field = [
                    'b.build_electricity_price',
                    'b.build_water_price'
                ];
                $room_join = [
                    ['__BUILD__ b', 'r.build_id = b.build_id']
                ];
                $room_where = [
                    'r.room_id' => $room_id,
                    'r.is_deleted' => '0'
                ];
                $room_data = $room_model->alias('r')->field($room_field)->join($room_join)->where($room_where)->find();

                //入住信息
                $check_in_model = model('CheckIn');
                $check_in_data = $check_in_model->get(['check_in_id' => $check_in_id]);
                $check_in_month = strtotime(date('Y-m', $check_in_data['check_in_date']));

                if ($settlement_electricity < $check_in_data['check_in_electricity']) $this->_data['error']['message'] = '该月份电量不能小于入住的电量';
                if ($settlement_water < $check_in_data['check_in_water']) $this->_data['error']['message'] = '该月份水量不能小于上次入住的水量';

                if (!$data['error']) {
                    //上次电量和水量使用信息
                    $settlement_where = [
                        'user_id' => $user_id,
                        'room_id' => $room_id,
                        'check_in_id' => $check_in_id,
                        'is_deleted' => '0'
                    ];
                    $settlement_order = [
                        'settlement_month' => 'desc'
                    ];
                    $last_month_settlement_data = $settlement_model->where($settlement_where)->order($settlement_order)->find();
                    $last_settlement_month = !$last_month_settlement_data ? $check_in_month : $last_month_settlement_data->settlement_month;
                    $last_settlement_month_electricity = !$last_month_settlement_data ? $check_in_data['check_in_electricity'] : $last_month_settlement_data->settlement_electricity;
                    $last_settlement_month_water = !$last_month_settlement_data ? $check_in_data['check_in_water'] : $last_month_settlement_data->settlement_water;

                    $settlement_list = [];

                    //月份差
                    list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$settlement_month));
                    list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$check_in_month));
                    $different_month = abs($date_1['y']-$date_2['y'])*12 + abs($date_2['m']-$date_1['m']);

                    for($i = 0; $i <= $different_month; $i++) {
                        $new_settlement_month = strtotime('+'.$i.' month', $last_settlement_month);
                        $new_settlement_last_electricity = 0;
                        $new_settlement_last_water = 0;
                        $new_settlement_electricity = 0;
                        $new_settlement_water = 0;
                        $new_settlement_electricity_amount = 0;
                        $new_settlement_water_amount = 0;
                        $new_settlement_additional_amount = 0;
                        $new_settlement_total_amount = $new_settlement_electricity_amount+$new_settlement_water_amount+$check_in_data['check_in_rent'];
                        $new_settlement_remark = '';

                        if ($new_settlement_month == $settlement_month) {
                            $new_settlement_month = $settlement_month;
                            $new_settlement_last_electricity = $last_settlement_month_electricity;
                            $new_settlement_last_water = $last_settlement_month_water;
                            $new_settlement_electricity = $settlement_electricity;
                            $new_settlement_water = $settlement_water;
                            $new_settlement_electricity_amount = ($settlement_electricity - $last_settlement_month_electricity)*$room_data['build_electricity_price'];
                            $new_settlement_water_amount = ($settlement_water - $last_settlement_month_water)*$room_data['build_water_price'];
                            $new_settlement_additional_amount = $settlement_additional_amount;
                            $new_settlement_total_amount = $new_settlement_electricity_amount+$new_settlement_water_amount+$check_in_data['check_in_rent']+$settlement_additional_amount;
                            $new_settlement_remark = $settlement_remark;
                        }

                        $settlement_list[] = [
                            'user_id' => $user_id,
                            'room_id' => $room_id,
                            'check_in_id' => $check_in_id,
                            'settlement_last_electricity' => $new_settlement_last_electricity,
                            'settlement_last_water' => $new_settlement_last_water,
                            'settlement_month' => $new_settlement_month,
                            'settlement_electricity' => $new_settlement_electricity,
                            'settlement_water' => $new_settlement_water,
                            'settlement_electricity_amount' => $new_settlement_electricity_amount,
                            'settlement_water_amount' => $new_settlement_water_amount,
                            'settlement_additional_amount' => $new_settlement_additional_amount,
                            'settlement_rent_amount' => $check_in_data['check_in_rent'],
                            'settlement_total_amount' => $new_settlement_total_amount,
                            'settlement_remark' => $new_settlement_remark
                        ];
                    }
                    $result = $settlement_model->saveAll($settlement_list);
                }
            }
        }

        return $result;
    }

    public function update()
    {
        $data = [];
        $data['error'] = [];
        $result = false;

        if (Request::instance()->isPost()) {
            $user_id = input('post.user_id');
            $room_id = input('post.room_id');
            $check_in_id = input('post.check_in_id');
            $settlement_id = input('post.settlement_id');
            $settlement_remark = input('post.settlement_remark');

            $settlement_model = model('Settlement');

            $result = $settlement_model->save([
                'settlement_remark' => $settlement_remark
            ], [
                'user_id' => $user_id,
                'room_id' => $room_id,
                'check_in_id' => $check_in_id,
                'settlement_id' => $settlement_id
            ]);
        }

        return $result;
    }

    public function save()
    {
        $data = [];
        $data['status'] = 428;

        if (Request::instance()->isPost()) {
            $settlement_id = input('post.settlement_id');

            $result = isset($settlement_id) && $settlement_id ? $this->update() : $this->create();
            $data['status'] = $result !== false ? 200 : 400;
        }

        return json($this->dataReturn($data));
    }

    public function ls()
    {
        $data = [];

        if (Request::instance()->isPost()) {
            $user_id = input('post.user_id');
            $room_id = input('post.room_id');
            $check_in_id = input('post.check_in_id');
            $per_page = 20;
            $page = input('post.page');

            $settlement_model = model('Settlement');

            $settlement_where = [
                'user_id' => $user_id,
                'room_id' => $room_id,
                'check_in_id' => $check_in_id,
                'settlement_status' => 1,
                'is_deleted' => '0'
            ];

            $settlement_order = [
                'settlement_month' => 'desc'
            ];

            $data['settlement'] = $settlement_model->where($settlement_where)->order($settlement_order)->limit(($page - 1) * $per_page, $per_page)->select();
            foreach ($data['settlement'] as $key => $settlement) {
                $data['settlement'][$key]['settlement_month'] = date('Y-m', $settlement['settlement_month']);
            }
            $data['status'] = 200;
        }

        return json($this->dataReturn($data));
    }

    public function get()
    {
        $data = [];

        if (Request::instance()->isPost()) {
            $user_id = input('post.user_id');
            $room_id = input('post.room_id');
            $settlement_id = input('post.settlement_id');

            $settlement_model = model('Settlement');

            $settlement_field = [
                's.*',
                'r.room_name',
                'b.build_address'
            ];

            $settlement_join = [
                ['__ROOM__ r', 'r.room_id = s.room_id'],
                ['__BUILD__ b', 'r.build_id = b.build_id']
            ];

            $settlement_where = [
                's.user_id' => $user_id,
                's.room_id' => $room_id,
                's.settlement_id' => $settlement_id,
                's.is_deleted' => '0'
            ];

            $data['settlement'] = $settlement_model->alias('s')->field($settlement_field)->join($settlement_join)->where($settlement_where)->find();

            if ($data['settlement']) {
                $data['settlement']['settlement_month'] = date('Y-m', $data['settlement']['settlement_month']);
            }
        }

        return json($this->dataReturn($data));
    }
}